package me.chenqiang.tre.expression;

import java.util.Collection;
import java.util.function.BiFunction;

import me.chenqiang.tre.entity.Card;
import me.chenqiang.tre.entity.Device;

/**
 * 用来表示“属于”或“不属于”的表达式
 * 
 * 表达式左侧的属性是单个字符串，右侧的属性是字符串集合。例如用于判断持卡人身份类型是否属于某几个类型之一。
 * 
 */
public class InExpression implements Expression {
	public enum Type {
		IN, NOT_IN
	}

	protected Type type;
	protected String propertyName;
	protected BiFunction<Card, Device, String> propertyGetter;
	protected Collection<String> propertyValues;

	public InExpression(Type type, String propertyName, BiFunction<Card, Device, String> propertyGetter,
			Collection<String> propertyValues) {
		super();
		this.type = type;
		this.propertyName = propertyName;
		this.propertyGetter = propertyGetter;
		this.propertyValues = propertyValues;
	}

	@Override
	public boolean evaluate(Card card, Device device) {
		String propertyValue = this.propertyGetter.apply(card, device);
		switch (this.type) {
		case IN:
			return propertyValues.contains(propertyValue);
		case NOT_IN:
			return !propertyValues.contains(propertyValue);
		default:
			throw new IllegalArgumentException(String.format("错误类型：%s", this.type));
		}
	}

	@Override
	public String getType() {
		return this.type.name();
	}

	@Override
	public String getPropertyName() {
		return this.propertyName;
	}

	@Override
	public String getPropertyValue() {
		return String.join(",", this.propertyValues);
	}
}
